package org.zjt.demo.elasticsearch;

import org.apache.log4j.Logger;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;

import java.net.InetAddress;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.matchQuery;

/**
 * Created by zhang on 2017/3/3.
 */

public class SeacherDocument {
    private static final Logger logger = Logger.getLogger(SeacherDocument.class);

    public static void main (String []agre) throws Exception {
        //http://bj1.lc.data.sankuai.com/ test 80 online 9300
        // on startup
        //连接到集群 初始化客户端
        TransportClient client = TransportClient.builder().build().addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));

        /*QueryBuilder queryBuilder = QueryBuilders
         .disMaxQuery()
         .add(QueryBuilders.termQuery("roomName", "豪华大床"))
         .add(QueryBuilders.termQuery("status", "0"));*/
        //查询条件 在匹配文字的时候一定用matchQuery termQuery 用于精确匹配 匹配数字 ，long型 term查询不会分词

        QueryBuilder qb = boolQuery().must(matchQuery("roomName", "豪华大房")) ;

        /* QueryBuilder qb = boolQuery()
         .must(matchQuery("roomName", "豪华大房"))
         .must(matchQuery("status", "0"))
         .must(matchQuery("sourceCode", "4"))
         .must(matchQuery("typeLimitValue", "5"))
         .must(matchQuery("soldPrice", "11673"));*/

        SearchResponse response = client.prepareSearch("hotel")   //hotel索引
                .setTypes("room")  //room type
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)   //搜索类型
                .setQuery(qb)              // Query
                .setPostFilter(QueryBuilders.rangeQuery("datetime").gte("2016-10-20").lte("2016-10-21").format("yyyy-MM-dd"))  //在查询到的结果后 进行日期过滤
                .setFrom(0).setSize(10).setExplain(true)  //分页
                .execute()  //执行
                .actionGet();

        long count =response.getHits().getTotalHits(); //命中的结果
        System.out.println(count);
        SearchHit[] hits =response.getHits().getHits();
        for (SearchHit hit : hits) {
            System.out.println(hit.getSource());
        }
    }

}

